<script setup>
import { ref, onMounted } from 'vue'
import {
  projectPageQueryService,
  deleteProjectService,
  updateProjectStatusService
} from '@/api/project.js'
import {
  Search,
  Refresh,
  Edit,
  Delete,
  Download,
  DCaret,
  CaretTop,
  CaretBottom
} from '@element-plus/icons-vue'
import { exportProjectStatisticsReportService } from '@/api/report'
import ProjectEdit from './components/ProjectEdit.vue'
import ProjectTypeSelect from './components/ProjectTypeSelect.vue'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'

const route = useRoute()

// 获取用户角色
const userStore = useUserStore()
const userRole = userStore.user.role

const projectList = ref([]) // 服务项目列表
const total = ref(0) // 总条数
const loading = ref(false) // loading状态

// 请求参数
const params = ref({
  pageNum: 1, // 当前页码
  pageSize: 10, // 每页条数
  orderBy: 'update_time', // 排序字段
  isAsc: false, // 是否升序
  name: null, // 服务项目名称
  projectTypeId: null, // 服务项目类型id
  status: null // 服务项目状态
})

// 基于params参数，获取服务项目列表
const getProjectList = async () => {
  loading.value = true
  const res = await projectPageQueryService(params.value)
  projectList.value = res.data.data.list
  total.value = res.data.data.total
  loading.value = false
}

// 初始化数据，可以接收路由参数
onMounted(() => {
  params.value.status = route.query.status || null
  getProjectList()
})

// 处理分页逻辑
const onPageSizeChange = (size) => {
  params.value.pageNum = 1
  params.value.pageSize = size
  getProjectList()
}
const onPageNumChange = (page) => {
  params.value.pageNum = page
  getProjectList()
}

// 处理排序逻辑
const handleSort = (field) => {
  if (params.value.isAsc === false && params.value.orderBy === field) {
    // 如果当前已经降序，则重置排序
    params.value.orderBy = null
    params.value.isAsc = null
  } else if (params.value.orderBy === field) {
    // 如果当前已经是按该字段排序，则切换升序/降序
    params.value.isAsc = !params.value.isAsc
  } else {
    // 如果是第一次点击该字段，则默认升序
    params.value.orderBy = field
    params.value.isAsc = true
  }
  // 重新获取数据
  getProjectList()
}

// 获取排序图标
const getSortIcon = (field) => {
  if (params.value.orderBy === field) {
    return params.value.isAsc ? CaretTop : CaretBottom
  }
  return DCaret
}

// 搜索逻辑
const handleSearch = () => {
  params.value.pageNum = 1
  getProjectList()
}

// 重置逻辑
const handleReset = () => {
  params.value = {
    ...params.value, // 保留其他属性
    pageNum: 1,
    name: null,
    projectTypeId: null,
    status: null
  }
  getProjectList()
}

const projectEditRef = ref()
// 新增逻辑
const handleAdd = () => {
  projectEditRef.value.open({})
}

// 编辑逻辑
const handleEdit = (row) => {
  projectEditRef.value.open(row)
}

// 删除逻辑
const handleDelete = async (row) => {
  await ElMessageBox.confirm('是否确认删除该服务项目？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deleteProjectService(row.id)
  ElNotification({
    title: '删除成功',
    type: 'success'
  })
  getProjectList()
}

// 修改服务项目状态
const handleStatusChange = async (row) => {
  try {
    await updateProjectStatusService(row.status, row.id)
    ElNotification({
      title: `${row.status}服务项目状态成功`,
      type: 'success'
    })
  } catch (error) {
    row.status = row.status === '启用' ? '禁用' : '启用'
  }
}

// 导出指定服务项目报表
const handleExportProjectReport = async (row) => {
  const response = await exportProjectStatisticsReportService(row.id)

  // 从响应头获取文件名（兼容不同格式）
  const contentDisposition = response.headers['content-disposition']
  let fileName = '服务项目统计报表.xlsx' // 默认文件名

  if (contentDisposition) {
    // 处理RFC5987编码格式（filename*=UTF-8''xxx）
    const utf8FilenameRegex = /filename\*=UTF-8''([^;]+)/i
    const utf8FilenameMatch = contentDisposition.match(utf8FilenameRegex)

    if (utf8FilenameMatch && utf8FilenameMatch[1]) {
      fileName = decodeURIComponent(utf8FilenameMatch[1])
    } else {
      // 处理普通格式（filename="xxx"或filename=xxx）
      const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i
      const filenameMatch = contentDisposition.match(filenameRegex)

      if (filenameMatch && filenameMatch[1]) {
        fileName = filenameMatch[1].replace(/['"]/g, '')
      }
    }
  }

  // 创建 Blob URL 并触发下载
  const blob = new Blob([response.data], {
    type: response.headers['content-type'] || 'application/octet-stream'
  })

  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName // 设置下载文件名
  document.body.appendChild(link)
  link.click()

  // 清理
  setTimeout(() => {
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  }, 100)
}
</script>

<template>
  <page-container title="服务项目管理">
    <template #extra>
      <el-button
        v-if="['管理员', '店长'].includes(userRole)"
        type="primary"
        plain
        @click="handleAdd"
        >新增服务项目</el-button
      >
    </template>
    <!-- 表单 -->
    <el-form inline>
      <el-form-item label="服务项目名称:">
        <el-input v-model="params.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="服务项目类型:">
        <project-type-select v-model="params.projectTypeId" width="200px" />
      </el-form-item>
      <el-form-item label="服务项目状态:">
        <el-select v-model="params.status" style="width: 100px">
          <el-option label="禁用" value="禁用"></el-option>
          <el-option label="启用" value="启用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch"></el-button>
        <el-button type="default" :icon="Refresh" @click="handleReset"></el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table class="tb" :data="projectList" v-loading="loading" :row-style="{ height: '50px' }">
      <el-table-column prop="id" label="服务项目ID" width="120">
        <template #header>
          <span>服务项目ID</span>
          <el-icon @click="handleSort('id')">
            <component :is="getSortIcon('id')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="服务项目名称" width="200" />
      <el-table-column prop="projectTypeName" label="服务项目类型" width="150" />
      <el-table-column prop="price" label="服务项目价格" width="150">
        <template #default="{ row }"> {{ (row.price / 100).toFixed(2) }}元 </template>
      </el-table-column>
      <el-table-column prop="status" label="服务项目状态" width="120">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-value="启用"
            inactive-value="禁用"
            active-text="启用"
            inactive-text="禁用"
            @click="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="description" label="服务项目描述" width="200" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #header>
          <span>创建时间</span>
          <el-icon @click="handleSort('create_time')">
            <component :is="getSortIcon('create_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #header>
          <span>更新时间</span>
          <el-icon @click="handleSort('update_time')">
            <component :is="getSortIcon('update_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column
        v-if="['管理员', '店长'].includes(userRole)"
        label="操作"
        width="180"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            :icon="Edit"
            plain
            size="small"
            @click="handleEdit(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            plain
            size="small"
            @click="handleDelete(row)"
          ></el-button>
          <el-button
            type="primary"
            :icon="Download"
            plain
            size="small"
            @click="handleExportProjectReport(row)"
          ></el-button>
        </template>
      </el-table-column>
      <!-- 空数据提示 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="onPageSizeChange"
      @current-change="onPageNumChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </page-container>
  <!-- 抽屉 -->
  <project-edit ref="projectEditRef" @success="handleReset"></project-edit>
</template>

<style lang="scss" scoped>
.tb {
  border-radius: 10px;
  box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
</style>
